﻿using System;
using System.Collections.Generic;
using CxExtension;
using UnityEngine;
using Pool = UnityExtensions.TransformPoolAsync;

namespace UnityExtensions
{
	public class UIPool
	{
		private readonly Dictionary<string, Pool> mPools = new Dictionary<string, Pool>(10);                      //
		private readonly Dictionary<Transform, Pool> mPoolMap = new Dictionary<Transform, Pool>(10);
		private Action<string, Action<Transform>> mLoadAction;
		private Func<Pool> mNewPoolAction;



		public void SetNewPoolAction(Func<Pool> v)
		{
			mNewPoolAction = v;
		}

		public void SetLoadAction(Action<string, Action<Transform>> v)
		{
			mLoadAction = v;
		}

		public UIPool()
		{
			
		}

		public UIPool(Action<string, Action<Transform>> loadAction)
		{
			this.mLoadAction = loadAction;
		}
		public void Get(string name, Action<Transform> func)
		{
			var pool = mPools.GetOrNewAdd(name, CreateNewPool);
			pool.Get((it) =>
			{
				mPoolMap[it] = pool;
				func(it);
			});
		}

		public Pool CreateNewPool(string key)
		{
			var pool = mNewPoolAction == null ? CreateNewPoolDefault() : mNewPoolAction();
			pool.SetUiName(key);
			if (mLoadAction == null)
			{
				Debug.LogErrorFormat("LoadAction is null");
			}
			if (pool.CreateNewAsync == null)
			{
				pool.CreateNewAsync = (call) => { mLoadAction(pool.UiName, call); };
			}
			return pool;
		}
		public static Pool CreateNewPoolDefault()
		{
			var pool = new Pool();
			pool.SetGetAction((it) =>
			{
				it.SetActive(true);
			});
			pool.SetResetAction((it) =>
			{
				it.SetActive(false);
				it.SetParent(pool.Parent,false);
			});
			return pool;
		}
		

		public bool Recycle(Transform item)
		{
			if (item == null) { return false; }

			Pool pool;
			if (mPoolMap.TryGetValue(item, out pool))
			{
				mPoolMap.Remove(item);
				pool.Recycle(item);
				return true;
			}

			Debug.LogErrorFormat("{0} not is Pool transform",item.name);

			return false;
		}
	}
}